﻿using Confluent.Kafka;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace MQHelper.Kafka
{
    public class KafkaProducer : IDisposable
    {
        private bool disposedValue;
        private IEnumerable<KeyValuePair<string, string>> _cnf;
        private IProducer<Null, string> _producer;

        public KafkaProducer(string host,string groupId)
        {
            _cnf = new Dictionary<string, string>
            {
              { "group.id", groupId },
              { "bootstrap.servers", host },
              //{ "auto.commit.interval.ms", commitInterval.ToString() },
              { "auto.offset.reset", "earliest" }
            };
        }

        public void Start()
        {
            ProducerBuilder<Null, string> builder = new ProducerBuilder<Null, string>(_cnf);
            _producer = builder.Build();
        }

        public async Task<bool> SendAsync(string topic, string data)
        {
            Message<Null, string> msg = new Message<Null, string>
            {
                Value = data,
                Timestamp = new Timestamp(DateTime.UtcNow),
            };
            msg.Value = data;
            DeliveryResult<Null, string> rs = await _producer.ProduceAsync(topic, msg);
            return true;
        }

        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    // TODO: 释放托管状态(托管对象)
                    _producer.Dispose();
                }
                // TODO: 释放未托管的资源(未托管的对象)并重写终结器
                // TODO: 将大型字段设置为 null
                disposedValue = true;
            }
        }

        // // TODO: 仅当“Dispose(bool disposing)”拥有用于释放未托管资源的代码时才替代终结器
        // ~KafkaProducer()
        // {
        //     // 不要更改此代码。请将清理代码放入“Dispose(bool disposing)”方法中
        //     Dispose(disposing: false);
        // }

        public void Dispose()
        {
            // 不要更改此代码。请将清理代码放入“Dispose(bool disposing)”方法中
            Dispose(disposing: true);
            GC.SuppressFinalize(this);
        }
    }
}